<?php
/**
 * 我的购物车
 *
 *
 *
 *
 */

//use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');

class member_cartControl extends mobileMemberControl {

	public function __construct() {
		parent::__construct();
	}
	
	/**
	 * 2016-12-09
	 * 返回是否促销商品
	 * @param unknown $goods_id 商品ID
	 */
	private function _is_discount($goods_id)
	{
	    //获得每一件购物车商品是否是促销商品
	    //$value['goods_id']
	    $model_goods = Model('goods');
	    $goods_info=$model_goods->getGoodsOnlineInfoForShare($goods_id);
	    return $goods_info['is_discount'];
	    //return $goods_info;
	}

    /**
     * 购物车列表
     */
    public function cart_listOp() {
         $model_cart = Model('cart');

        // $condition = array('buyer_id' => $this->member_info['member_id']);
        
        // $cart_list	= $model_cart->listCart('db', $condition);
        

        $logic_buy_1 = logic('buy_1');
        $cart_list  = $model_cart->listCart('db',array('buyer_id'=> $this->member_info['member_id']));
        $cart_list = $logic_buy_1->getGoodsCartList($cart_list);
        $sum = 0;
        foreach ($cart_list as $key => $value) {
            $cart_list[$key]['goods_storage'] = $this->_get_goods_storage($value,$value['goods_num'],$value['buyer_id']);
            $cart_list[$key]['goods_image_url'] = cthumb($value['goods_image'], $value['store_id']);
            $cart_list[$key]['goods_sum'] = ncPriceFormat($value['goods_price'] * $value['goods_num']);
            
            
            $cart_list[$key]['is_discount']=$this->_is_discount($value['goods_id']);
            
            $sum += $cart_list[$key]['goods_sum'];
        }
        
        $goods_model=Model('goods');
        $goods_list = $goods_model->getGoodsOnlineList(array(), '*', 0, 'goods_id desc', 4, null, false);
        foreach ($goods_list as $key=>$val){
            //切割图片路径
            $img = explode(".", $val['goods_image']);//得到名称和后缀
            $goods_list[$key]['goods_image']=UPLOAD_SITE_URL.'/shop/store/goods/1/'.$val['goods_image'];
        }

        output_data(array('cart_list' => $cart_list, 'sum' => ncPriceFormat($sum),'goods_list'=>$goods_list));
        
    }

    /**
     * 购物车添加
     */
  //   public function cart_add1Op() {
  //       $goods_id = intval($_POST['goods_id']);
  //       $quantity = intval($_POST['quantity']);
  //       $bl_id=intval($_POST['bl_id']);
  //       if($goods_id <= 0 || $quantity <= 0||$bl_id <= 0) {
  //           output_error('参数错误');
  //       }

  //       $model_goods = Model('goods');
  //       $model_cart	= Model('cart');
  //       $logic_buy_1 = Logic('buy_1');

  //       $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($goods_id);

  //       //验证是否可以购买
		// if(empty($goods_info)) {
  //           output_error('商品已下架或不存在');
		// }

		// //抢购
		// $logic_buy_1->getGroupbuyInfo($goods_info);
		
		// //限时折扣
		// $logic_buy_1->getXianshiInfo($goods_info,$quantity);

        
  //       if ($goods_info['store_id'] == $this->member_info['store_id']) {
  //           output_error('不能购买自己发布的商品');
		// }
		// if(intval($goods_info['goods_storage']) < 1 || intval($goods_info['goods_storage']) < $quantity) {
  //           output_error('库存不足');
		// }

  //       $param = array();
  //       $param['buyer_id']	= $this->member_info['member_id'];
  //       $param['store_id']	= $goods_info['store_id'];
  //       $param['goods_id']	= $goods_info['goods_id'];
  //       $param['goods_name'] = $goods_info['goods_name'];
  //       $param['goods_price'] = $goods_info['goods_price'];
  //       $param['goods_image'] = $goods_info['goods_image'];
  //       $param['store_name'] = $goods_info['store_name'];

  //       $result = $model_cart->addCart($param, 'db', $quantity);
  //       if($result) {
  //           output_data(array("msg"=>"操作成功！"));
  //       } else {
  //           output_error('添加失败');
  //       }
  //   }
    /**
     * 购物车添加
     */
    public function cart_addOp() {  
        
        $model_goods = Model('goods');
        
        $logic_buy_1 = Logic('buy_1');

        $model_cart=Model('cart');
        $quantity = intval($_POST['quantity']);
        
        if (is_numeric($_POST['goods_id'])) {
           
          //查找购物车是否有这个商品
          $where['goods_id']=$_POST['goods_id'];
          $where['buyer_id']=$this->member_info['member_id'];
          
          $ifgoods=$model_cart->checkCart($where);
          
          //查找该商品是否促销商品
          //$_POST['goods_id']      
          $is_discount=$this->_is_discount($_POST['goods_id']);
          if($is_discount){
              if($ifgoods){
                  //购物车中已经有该商品
                  output_error('促销商品只能购买一份哦!');
              }
              
              //判断以往是否购买过该商品
              $order=Model('order');
              //获得用户id
              $condition['buyer_id'] = $where['buyer_id'];
              //获得商品id
              $condition['goods_id'] = $_POST['goods_id'];
              //获得数组
              $result=$order->get_oeder_good($condition);
              if ($result['goods_id']){
                  output_error('您已购买过该促销商品!');
              }

          }
          
          
          //有就直接数量增加
          if($ifgoods){
              $cart_info=$model_cart->getCartInfo($where);
              //保存用户操作商品的行为
              $data_f['fever_goodsid']=$cart_info['goods_id'];
              $data_f['fever_goodsname']=$cart_info['goods_name'];
              $data_f['fever_goodsprice']=$cart_info['goods_price'];
              $data_f['fever_actid']=$_POST['actid'];
              $data_f['fever_acttype']=$_POST['acttype'];
              $data_f['fever_actname']=$_POST['actname'];
              $data_f['fever_actiontype']=2;
              $data_f['fever_actiontime']=TIMESTAMP;
              $data_f['client']=$_POST['client'];
              $data_f['fever_actionip']=$_SERVER["REMOTE_ADDR"];
              $data_f['fever_actionmobile']=$this->member_info['member_mobile'];
              $model_fever=Model('fever');
              $result=$model_fever->saveFever($data_f);
              
            $data['goods_num']=$ifgoods['goods_num']+$quantity;

            $update=$model_cart->editCart($data,$where);
            
            if($update) {
              output_data(array("msg"=>"操作成功！"));

            } else {
                output_error('添加失败');
            }
          }

            //商品加入购物车(默认)
            $goods_id = intval($_POST['goods_id']);
            
            if ($goods_id <= 0) return ;
            $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($goods_id);

            //保存用户操作商品的行为
            $data_f['fever_goodsid']=$goods_info['goods_id'];
            $data_f['fever_goodsname']=$goods_info['goods_name'];
            $data_f['fever_goodsprice']=$goods_info['goods_price'];
            $data_f['fever_actid']=$_POST['actid'];
            $data_f['fever_acttype']=$_POST['acttype'];
            $data_f['fever_actname']=$_POST['actname'];
            $data_f['fever_actiontype']=2;
            $data_f['fever_actiontime']=TIMESTAMP;
            $data_f['client']=$_POST['client'];
            $data_f['fever_actionip']=$_SERVER["REMOTE_ADDR"];
            $data_f['fever_actionmobile']=$this->member_info['member_mobile'];
            $model_fever=Model('fever');
            $result=$model_fever->saveFever($data_f);
            
            //抢购
            $logic_buy_1->getGroupbuyInfo($goods_info);

            //限时折扣
            $logic_buy_1->getXianshiInfo($goods_info,$quantity);

            

        } elseif (is_numeric($_POST['bl_id'])) {//套餐
           
            //优惠套装加入购物车(单套)
           
            $bl_id = intval($_POST['bl_id']);

            //查找购物车是否有这个商品
          $where['bl_id']=$_POST['bl_id'];
          $where['buyer_id']=$this->member_info['member_id'];
          $ifgoods=$model_cart->checkCart($where);

          //有就直接数量增加
          if($ifgoods){
              $cart_info=$model_cart->getCartInfo($condition);
              //保存用户操作商品的行为
              $data_f['fever_goodsid']=$cart_info['goods_id'];
              $data_f['fever_goodsname']=$cart_info['goods_name'];
              $data_f['fever_goodsprice']=$cart_info['goods_price'];
              $data_f['fever_actid']=$_POST['actid'];
              $data_f['fever_acttype']=$_POST['acttype'];
              $data_f['fever_actname']=$_POST['actname'];
              $data_f['fever_actiontype']=2;
              $data_f['fever_actiontime']=TIMESTAMP;
              $data_f['client']=$_POST['client'];
              $data_f['fever_actionip']=$_SERVER["REMOTE_ADDR"];
              $data_f['fever_actionmobile']=$this->member_info['member_mobile'];
              $model_fever=Model('fever');
              $result=$model_fever->saveFever($data_f);
              
              
            $data['goods_num']=$ifgoods['goods_num']+$quantity;
            
            $update=$model_cart->editCart($data,$where);
            if($update) {
              output_data(array("msg"=>"操作成功！"));

            } else {
                output_error('添加失败');
            }
          }

            if ($bl_id <= 0) return ;
            $model_bl = Model('p_bundling');
            $bl_info = $model_bl->getBundlingInfo(array('bl_id'=>$bl_id));
            if (empty($bl_info) || $bl_info['bl_state'] == '0') {
                output_error('该优惠套装已不存在，建议您单独购买');
            }

            //检查每个商品是否符合条件,并重新计算套装总价
            $bl_goods_list = $model_bl->getBundlingGoodsList(array('bl_id'=>$bl_id));
            $goods_id_array = array();
            $bl_amount = 0;
            foreach ($bl_goods_list as $goods) {
                $goods_id_array[] = $goods['goods_id'];
                $bl_amount += $goods['bl_goods_price'];
            }
            $model_goods = Model('goods');
            $goods_list = $model_goods->getGoodsOnlineListAndPromotionByIdArray($goods_id_array);
            
            //优惠套装作为一条记录插入购物车，图片取套装内的第一个商品图
            $goods_info    = array();
            $goods_info['store_id'] = $bl_info['store_id'];
            $goods_info['goods_id'] = $goods_list[0]['goods_id'];
            $goods_info['goods_name'] = $bl_info['bl_name'];
            $goods_info['goods_price'] = $bl_amount;
            $goods_info['goods_num']   = 1;
            $goods_info['goods_image'] = $goods_list[0]['goods_image'];
            $goods_info['store_name'] = $bl_info['store_name'];
            $goods_info['bl_id'] = $bl_id;
            $quantity = 1;
            
            //保存用户操作商品的行为  
            $data_f['fever_goodsid']=$goods_list[0]['goods_id'];
            $data_f['fever_goodsname']=$goods_list[0]['goods_name'];
            $data_f['fever_goodsprice']=$goods_list[0]['goods_price'];
            $data_f['fever_actid']=$_POST['actid'];
            $data_f['fever_acttype']=$_POST['acttype'];
            $data_f['fever_actname']=$_POST['actname'];
            $data_f['fever_actiontype']=2;
            $data_f['fever_actiontime']=TIMESTAMP;
            $data_f['client']=$_POST['client'];
            $data_f['fever_actionip']=$_SERVER["REMOTE_ADDR"];
            $data_f['fever_actionmobile']=$this->member_info['member_mobile'];
            $model_fever=Model('fever');
            $result=$model_fever->saveFever($data_f);

        }
        
        $goods_info['buyer_id'] = $this->member_info['member_id'];
        $model_cart    = Model('cart');
        
        $insert = $model_cart->addCart($goods_info,'db',$quantity);
        if($insert) {
            output_data(array("msg"=>"操作成功！"));
        } else {
            output_error('添加失败');
        }
    }
    /**
     * 购物车删除
     */
    public function cart_delOp() {
        $cart_id = intval($_POST['cart_id']);

        $model_cart = Model('cart');

        if($cart_id > 0) {
            
            
            
            $condition = array();
            $condition['buyer_id'] = $this->member_info['member_id'];
            $condition['cart_id'] = $cart_id;

            $cart_info=$model_cart->getCartInfo($condition);
            //保存用户操作商品的行为
            $data['fever_goodsid']=$cart_info['goods_id'];
            $data['fever_goodsname']=$cart_info['goods_name'];
            $data['fever_goodsprice']=$cart_info['goods_price'];
            $data['fever_actid']=$_POST['actid'];
            $data['fever_acttype']=$_POST['acttype'];
            $data['fever_actname']=$_POST['actname'];
            $data['fever_actiontype']=3;
            $data['fever_actiontime']=TIMESTAMP;
            $data['fever_actionip']=$_SERVER["REMOTE_ADDR"];
            $data['client']=$_POST['client'];
            $data['fever_actionmobile']=$this->member_info['member_mobile'];
            $model_fever=Model('fever');
            $result=$model_fever->saveFever($data);
            
            $model_cart->delCart('db', $condition);
        }

        output_data(array("msg"=>"操作成功！"));
    }

    /**
     * 更新购物车购买数量
     */
    public function cart_edit_quantityOp() {
		$cart_id = intval(abs($_POST['cart_id']));
		$quantity = intval(abs($_POST['quantity']));
		if(empty($cart_id) || empty($quantity)) {
            output_error('参数错误');
		}

		$model_cart = Model('cart');

        $cart_info = $model_cart->getCartInfo(array('cart_id'=>$cart_id, 'buyer_id' => $this->member_info['member_id']));

        //检查是否为本人购物车
        if($cart_info['buyer_id'] != $this->member_info['member_id']) {
            output_error('参数错误');
        }

        //检查库存是否充足
        if(!$this->_check_goods_storage($cart_info, $quantity, $this->member_info['member_id'])) {
            output_error('库存不足');
        }

		$data = array();
        $data['goods_num'] = $quantity;
        $update = $model_cart->editCart($data, array('cart_id'=>$cart_id));
		if ($update) {
		    $return = array();
            $return['quantity'] = $quantity;
			$return['goods_price'] = ncPriceFormat($cart_info['goods_price']);
			$return['total_price'] = ncPriceFormat($cart_info['goods_price'] * $quantity);
            output_data($return);
		} else {
            output_error('修改失败');
		}
    }

    /**
     * 检查库存是否充足
     */
    private function _check_goods_storage($cart_info, $quantity, $member_id) {
		$model_goods= Model('goods');
        $model_bl = Model('p_bundling');
        $logic_buy_1 = Logic('buy_1');

		if ($cart_info['bl_id'] == '0') {
            //普通商品
		    $goods_info	= $model_goods->getGoodsOnlineInfoAndPromotionById($cart_info['goods_id']);

		    //抢购
		    $logic_buy_1->getGroupbuyInfo($goods_info);

		    //限时折扣
		    $logic_buy_1->getXianshiInfo($goods_info,$quantity);
 
		    $quantity = $goods_info['goods_num'];
		    if(intval($goods_info['goods_storage']) < $quantity) {
                return false;
		    }
		} else {
		    //优惠套装商品
		    $bl_goods_list = $model_bl->getBundlingGoodsList(array('bl_id' => $cart_info['bl_id']));
		    $goods_id_array = array();
		    foreach ($bl_goods_list as $goods) {
		        $goods_id_array[] = $goods['goods_id'];
		    }
		    $bl_goods_list = $model_goods->getGoodsOnlineListAndPromotionByIdArray($goods_id_array);

		    //如果有商品库存不足，更新购买数量到目前最大库存
		    foreach ($bl_goods_list as $goods_info) {
		        if (intval($goods_info['goods_storage']) < $quantity) {
                    return false;
		        }
		    }
		}
        return true;
    }

    /**
     * 获取商品库存
     */
    private function _get_goods_storage($cart_info, $quantity, $member_id) {
        $model_goods= Model('goods');
        $model_bl = Model('p_bundling');
        $logic_buy_1 = Logic('buy_1');

        if ($cart_info['bl_id'] == '0') {
            //普通商品
            $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($cart_info['goods_id']);
            //抢购
            $logic_buy_1->getGroupbuyInfo($goods_info);
            //限时折扣
            $logic_buy_1->getXianshiInfo($goods_info,$quantity);
            $quantity = $goods_info['goods_num'];
            return intval($goods_info['goods_storage']);
        } else {
            //优惠套装商品
            $bl_goods_list = $model_bl->getBundlingGoodsList(array('bl_id' => $cart_info['bl_id']));
            $goods_id_array = array();
            foreach ($bl_goods_list as $goods) {
                $goods_id_array[] = $goods['goods_id'];
            }
            $bl_goods_list = $model_goods->getGoodsOnlineListAndPromotionByIdArray($goods_id_array);

            //如果有商品库存不足，更新购买数量到目前最大库存
            foreach ($bl_goods_list as $goods_info) {
                return array('goods_id'=>$goods_info['goods_id'],'goods_storage'=>intval($goods_info['goods_storage']));
            }
        }
    }
    
    function getCartNumOp() {
        $model_cart = Model('cart');
        $logic_buy_1 = logic('buy_1');
        $cart_list  = $model_cart->listCart('db',array('buyer_id'=> $this->member_info['member_id']));
        $cart_list = $logic_buy_1->getGoodsCartList($cart_list);
        $num = 0;
        foreach ($cart_list as $key => $value) {
            if($value['storage_state']) {
                $num += $value['goods_num'];
            }
        }
        
        output_data(array('num' => $num));
        
    }

}
